<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="司机姓名" prop="driverName">
        <el-input
          v-model="queryParams.driverName"
          placeholder="请输入司机姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="服务名称" prop="serviceName">
        <el-input
          v-model="queryParams.serviceName"
          placeholder="请输入服务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="事件类型" prop="eventType">
        <el-select
          v-model="queryParams.eventType"
          placeholder="请选择事件类型"
          clearable
          size="small"
        >
          <el-option label="连接" value="connect" />
          <el-option label="断开" value="disconnect" />
          <el-option label="消息" value="message" />
          <el-option label="错误" value="error" />
        </el-select>
      </el-form-item>

      <el-form-item label="日志类型" prop="logType">
        <el-select
          v-model="queryParams.logType"
          placeholder="请选择日志类型"
          clearable
          size="small"
        >
          <el-option label="系统日志" value="system" />
          <el-option label="用户操作" value="user" />
          <el-option label="错误日志" value="error" />
          <el-option label="调试日志" value="debug" />
        </el-select>
      </el-form-item>

      <el-form-item label="在线状态" prop="onlineStatus">
        <el-select
          v-model="queryParams.onlineStatus"
          placeholder="请选择在线状态"
          clearable
          size="small"
        >
          <el-option label="在线" value="1" />
          <el-option label="离线" value="0" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClear"
        >清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
        >刷新</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      border
      :data="logList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      stripe
      highlight-current-row
    >
      <el-table-column type="selection" align="center" width="50" />

      <el-table-column label="司机信息" align="center"  fixed="left">
        <template slot-scope="scope">
          <div class="driver-info">
            <div class="driver-name">{{ scope.row.driverName || '-' }}</div>
            <div class="driver-id">ID: {{ scope.row.driverId || '-' }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="服务信息" align="center" >
        <template slot-scope="scope">
          <div class="service-info">
            <div class="service-name">{{ scope.row.serviceName || '-' }}</div>
            <div class="service-id">ID: {{ scope.row.serviceId || '-' }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="事件类型" align="center" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getEventTypeTag(scope.row.eventType)"
            size="mini"
          >
            {{ getEventTypeName(scope.row.eventType) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="日志类型" align="center" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getLogTypeTag(scope.row.logType)"
            size="mini"
          >
            {{ getLogTypeName(scope.row.logType) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="在线状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.onlineStatus === 1 ? 'success' : 'danger'"
            size="mini"
          >
            {{ scope.row.onlineStatus === 1 ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="消息内容" align="center" prop="message" show-overflow-tooltip width="200" />

      <el-table-column label="会话ID" align="center" prop="sessionId" show-overflow-tooltip width="150" />

      <el-table-column label="IP地址" align="center" prop="ipAddress" width="130" />

      <el-table-column label="创建时间" align="center" prop="createTime"  />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="WebSocket日志详情"
      :visible.sync="detailOpen"
      width="60%"
      append-to-body
      custom-class="log-detail-dialog"
    >
      <div class="detail-container" v-if="detailData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">
            {{ detailData.id }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ detailData.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="司机ID">
            {{ detailData.driverId || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="司机姓名">
            {{ detailData.driverName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="服务ID">
            {{ detailData.serviceId || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="服务名称">
            {{ detailData.serviceName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="事件类型">
            <el-tag :type="getEventTypeTag(detailData.eventType)" size="mini">
              {{ getEventTypeName(detailData.eventType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="日志类型">
            <el-tag :type="getLogTypeTag(detailData.logType)" size="mini">
              {{ getLogTypeName(detailData.logType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="会话ID" :span="2">
            {{ detailData.sessionId }}
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ detailData.ipAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="在线状态">
            <el-tag :type="detailData.onlineStatus === 1 ? 'success' : 'danger'" size="mini">
              {{ detailData.onlineStatus === 1 ? '在线' : '离线' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="消息内容" :span="2">
            <div class="message-content">
              {{ detailData.message || '-' }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  getOnlineSessionsList,
  deleteWebSocketLog,
  exportWebSocketLog,
  clearWebSocketLog
} from "@/api/websocketLog";

export default {
  name: "WebSocketLog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // WebSocket日志表格数据
      logList: [],
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情数据
      detailData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        driverName: null,
        serviceName: null,
        eventType: null,
        logType: null,
        onlineStatus: null
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 查询WebSocket日志列表
     */
    getList() {
      this.loading = true;
      getOnlineSessionsList(this.queryParams).then((response) => {
        this.logList = response.data || response.rows || response;
        this.total = response.total || (Array.isArray(response) ? response.length : 0);
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /**
     * 搜索按钮操作
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /**
     * 重置按钮操作
     */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /**
     * 多选框选中数据
     */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    /**
     * 查看按钮操作
     */
    handleView(row) {
      this.detailData = { ...row };
      this.detailOpen = true;
    },

    /**
     * 删除按钮操作
     */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除WebSocket日志编号为"' + ids + '"的数据项？')
        .then(function () {
          return deleteWebSocketLog(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /**
     * 导出按钮操作
     */
    handleExport() {
      this.download(
        "/api/websocketLog/export",
        {
          ...this.queryParams,
        },
        `websocket_log_${new Date().getTime()}.xlsx`
      );
    },

    /**
     * 清空按钮操作
     */
    handleClear() {
      this.$modal
        .confirm('是否确认清空所有WebSocket日志数据？')
        .then(function () {
          return clearWebSocketLog();
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("清空成功");
        })
        .catch(() => {});
    },

    /**
     * 刷新按钮操作
     */
    handleRefresh() {
      this.getList();
      this.$modal.msgSuccess("刷新成功");
    },

    /**
     * 获取事件类型标签样式
     */
    getEventTypeTag(eventType) {
      const tagMap = {
        'connect': 'success',
        'disconnect': 'danger', 
        'message': 'primary',
        'error': 'danger'
      };
      return tagMap[eventType] || 'info';
    },

    /**
     * 获取事件类型名称
     */
    getEventTypeName(eventType) {
      const nameMap = {
        'connect': '连接',
        'disconnect': '断开',
        'message': '消息', 
        'error': '错误'
      };
      return nameMap[eventType] || eventType || '-';
    },

    /**
     * 获取日志类型标签样式
     */
    getLogTypeTag(logType) {
      const tagMap = {
        'system': 'primary',
        'user': 'success',
        'error': 'danger',
        'debug': 'warning'
      };
      return tagMap[logType] || 'info';
    },

    /**
     * 获取日志类型名称
     */
    getLogTypeName(logType) {
      const nameMap = {
        'system': '系统日志',
        'user': '用户操作',
        'error': '错误日志', 
        'debug': '调试日志'
      };
      return nameMap[logType] || logType || '-';
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.log-detail-dialog {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.log-detail-dialog >>> .el-dialog__header {
  padding: 16px 20px;
  background: linear-gradient(135deg, #1890ff, #0050b3);
  margin-right: 0;
}

.log-detail-dialog >>> .el-dialog__title {
  color: #ffffff;
  font-weight: 600;
  font-size: 18px;
}

.log-detail-dialog >>> .el-dialog__headerbtn .el-dialog__close {
  color: #ffffff;
  font-size: 20px;
}

.log-detail-dialog >>> .el-dialog__body {
  padding: 30px 20px;
}

.log-detail-dialog >>> .el-dialog__footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.detail-container {
  padding: 0;
}

.driver-info,
.service-info {
  text-align: center;
  line-height: 1.5;
}

.driver-name,
.service-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  font-size: 14px;
}

.driver-id,
.service-id {
  font-size: 12px;
  color: #909399;
}

.message-content {
  max-height: 100px;
  overflow-y: auto;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  word-break: break-all;
  white-space: pre-wrap;
}

.el-tag {
  margin: 2px;
}

.dialog-footer {
  text-align: center;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table >>> .el-table__header th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

.el-table >>> .el-table__row:hover > td {
  background-color: #f5f7fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-form--inline .el-form-item {
    width: 100%;
    margin-right: 0;
  }
  
  .el-table >>> .el-table__column--selection {
    display: none;
  }
}
</style>
